const Websocket = function (options) {
    this.defaults = {
        url: "127.0.0.1:12015/webSocket/",

        // callbacks
        onOpen: function () {
        },
        onClose: function () {
        },
        onMessage: function (e) {
        },
        onError: function (e) {
        }
    }

    const opt = $.extend({}, this.defaults, options);
    const _this = this;
    let websocket = null;
    let lockReconnect = false;
    const timeout = 30 * 1000;
    const connectionId = randomString(10);

    let heartbeatTimeout = null;//心跳心跳倒计时
    let serverTimeout = null;//心跳倒计时
    let timeoutnum = null;//断开 重连倒计时


    function start() { // 开启心跳
        heartbeatTimeout && clearTimeout(heartbeatTimeout);
        heartbeatTimeout = setTimeout(() => {
            // 这里发送一个心跳，后端收到后，返回一个心跳消息，
            if (websocket && websocket.readyState == 1) { // 如果连接正常
                sendMessage({
                    type: 0,
                    connectionId: connectionId
                });
            } else { // 否则重连
                reconnect();
            }
            serverTimeout = setTimeout(() => {
                //超时关闭
                console.log("服务器超时，关闭连接");
                websocket.close();
            }, timeout * 2);

        }, timeout)
    };


    function reset() { // 重置心跳
        // 清除时间
        clearTimeout(heartbeatTimeout);
        clearTimeout(serverTimeout);
        // 重启心跳
        start();
    }


    function reconnect() { // 重新连接

        if (lockReconnect) return;
        console.log("重新建立连接");
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        timeoutnum && clearTimeout(timeoutnum);
        timeoutnum = setTimeout(() => {
            //新连接
            _this.connect();
            lockReconnect = false;
        }, 5000);
    }

    this.connect = function () {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("初始化websocket连接");
            // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
            const url = "ws://" + opt.url + connectionId + "/";
            try {
                websocket = new WebSocket(url);
                websocket.onopen = websocketOnOpen;
                websocket.onerror = websocketOnError;
                websocket.onmessage = websocketOnMessage;
                websocket.onclose = websocketClose;
                // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = this.onbeforeunload
            } catch (e) {
                console.error("建立websocket错误" + e);
            }
        }
    };


    function websocketOnMessage(event) {
        let data = JSON.parse(event.data);
        switch (data.type) {
            case 0:
                //收到服务器信息，心跳重置
                reset();
                break;
            case 1:
                break;
            default :
                opt.onMessage(data);
                console.log("接收到的服务器消息")
        }
    }

    function websocketOnOpen() {
        //开启心跳
        start();
        opt.onOpen();
        console.log("WebSocket连接成功!!!" + new Date() + "----" + websocket.readyState);
    }

    function websocketOnError(e) {
        opt.onError(e);
        console.log("WebSocket连接发生错误");
    }

    function websocketClose(e) {
        websocket.close();
        reconnect();
        opt.onClose();
        console.log("connection closed");
    }

    function closeWebSocket() { // 关闭websocket
        websocket.close()
    }

    function sendMessage(message) {
        websocket.send(JSON.stringify(message))
    }

    function randomString(length) {
        const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let result = '';
        for (let i = length; i > 0; --i)
            result += str[Math.floor(Math.random() * str.length)];
        return result;
    }

};
